package com.demo.java.quartz;

import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

/**
 * 自定义quartz调度
 */
@Slf4j
public class CustomQuartzTest {
    public static void main(String[] args) throws Exception {
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();

        JobDescription jobDescription = JobDescription.builder()
                .jobName("job")
                .jobGroup("test_job")
                .cron("* * * * * ? *").build();

        JobDetail jobDetail = jobDescription.jobDetail();
        CronTrigger trigger = jobDescription.trigger();

//        scheduler.addJob(jobDetail, true);

        scheduler.scheduleJob(jobDetail, trigger);

        Thread.sleep(5000L);

        JobDescription jobDescription1 = JobDescription.builder()
                .jobName("job1")
                .jobGroup("test_job")
                .cron("0/2 * * * * ? *").build();

        JobDetail jobDetail1 = jobDescription1.jobDetail();
        Trigger trigger1 = jobDescription1.trigger();

        scheduler.scheduleJob(jobDetail1, trigger1);

        scheduler.start();
    }

    @Data
    @Builder
    public static class JobDescription {
        private String jobName;
        private String jobGroup;
        private String cron;

        public JobKey jobKey() {
            return JobKey.jobKey(this.jobName, this.jobGroup);
        }

        public TriggerKey triggerKey() {
            return TriggerKey.triggerKey(this.jobName, this.jobGroup);
        }
        public JobDetail jobDetail() {
            return JobBuilder.newJob(TaskJob.class)/*.withIdentity(this.jobKey()).storeDurably()*/.build();
        }
        public CronTrigger trigger() {
            return TriggerBuilder.newTrigger()
                    .startNow()
                    .withIdentity(this.triggerKey())
                    .withSchedule(CronScheduleBuilder.cronSchedule(this.getCron()))
                    .build();
        }
    }

    public static class TaskJob implements Job {
        @Override
        public void execute(JobExecutionContext ctx) throws JobExecutionException {
            JobKey jobKey = ctx.getJobDetail().getKey();
            log.info("====== execute job, " + jobKey.getName());
        }
    }
}
